package service

import (
	"seat-service/initialization"
	"seat-service/model"
	"seat-service/model/dto"
)

type BuildingServiceImpl struct {
}

func (*BuildingServiceImpl) GetByClassroomId(id uint) (building model.Building, err error) {
	err = initialization.DB.Model(&model.Classroom{}).Select("buildings.*").Where("classrooms.id = ?", id).Joins("join buildings on buildings.id = classrooms.building_id").Find(&building).Error
	return
}

func (b *BuildingServiceImpl) GetAll() (buildings []model.Building, err error) {
	err = initialization.DB.Find(&buildings).Error
	return
}

func (b *BuildingServiceImpl) GetByCampusId(id int) (buildings []dto.NewBuildingInfDto, err error) {
	// TODO 改动 增加新字段（教室和座位数量）   根据校区id获取所有的教学楼
	//err = initialization.DB.Where("campus_id = ?", id).Find(&buildings).Error
	initialization.DB.Debug().Table("campus").
		Select("buildings.*,COUNT(DISTINCT classrooms.id) AS classroom_count, COUNT(seats.id) AS total_seats").
		Joins("JOIN buildings ON campus_id = ?", id).
		Joins("LEFT JOIN classrooms ON buildings.id = classrooms.building_id").
		Joins("LEFT JOIN seats ON classrooms.id = seats.classroom_id").
		Where("campus.id = ? AND classrooms.deleted_at is null AND seats.deleted_at is null", id).
		Group("campus.id, buildings.id").
		Scan(&buildings)
	return
}

// Query par 可能为 教室名 校区名
func (b *BuildingServiceImpl) Query(par string) (buildings []model.Building, err error) {
	err = initialization.DB.Table("buildings").Joins("join campus on buildings.campus_id = campus.id").Where("buildings.name like ? OR campus.campus_name like ?", "%"+par+"%", "%"+par+"%").Find(&buildings).Error
	return
}
